package controller;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Address;
import model.UserAccount;
import util.Log;
import validator.AddressValidator;
import web.AddressParser;
import web.JSONMessage;
import db.ImbiConnection;

public class AddressController extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {	
		UserAccount u = (UserAccount) request.getSession().getAttribute("user");		
		if(u != null){		
			AddressValidator validator = null;
			ArrayList<Address> list = AddressParser.parse(request);
			boolean error = false;
			for(Address a: list){
				System.out.println(a+" "+a.getId()+" "+a.getAddressType()+" "+a.getSubject()+" "+a.getSubjectType());
				validator = new AddressValidator(a);
				if(validator.isValid()){
					ImbiConnection.getAddressDAO().update(a);		
					Log.write(u.getUsername()+" updated "+a);
				} else if(validator.isValidNewAddress()){
					ImbiConnection.getAddressDAO().insert(a);
					Log.write(u.getUsername()+" inserted "+a);
				} 
				error = error | !validator.isValid();
			}		
			if(!error)response.getWriter().write(JSONMessage.message("Update Successful"));
			else response.getWriter().write(JSONMessage.errorMessage("Invalid parameters"));
		}
	}		
	
	@Override
	protected void doDelete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {		
		UserAccount u = (UserAccount) request.getSession().getAttribute("user");		
		if(u != null){
			try{			
				int id = extractId(request);  
				Address a = ImbiConnection.getAddressDAO().find(id);
				if(a != null){					
					ImbiConnection.getAddressDAO().delete(a);
					Log.write(u.getUsername()+" deleted "+a);
				}
			} catch(Exception e){ }
		}
		
	}

	private int extractId(HttpServletRequest request) throws IOException {
		BufferedInputStream asd= new BufferedInputStream(request.getInputStream());
		int b;
		StringBuilder strb = new StringBuilder();
		while((b = asd.read()) != -1){
			strb.append((char)b);
		}		
		return Integer.parseInt(strb.toString().split("=")[1]);
	}
}
